/*
 * TManager.cpp
 *
 *  Created on: 17.02.2011
 *      Author: dis
 */
#include <iostream>
#include <unistd.h>
#include "Activity.h"
#include "os/AbstractOS.h"
#include "TManager.h"
#include <curl/curl.h>
#include <curl/types.h>
#include <curl/easy.h>
#include <string.h>

using namespace std;

void sendPostInfo(Activity* newActivity){
	static char buffer[8*1024] = "data=";
		  newActivity->toJSON(buffer+5,8*1024);

	CURL *curl;
	  CURLcode res;

	  struct curl_slist *headerlist=NULL;
	  static const char buf[] = "Expect:";

	  curl_global_init(CURL_GLOBAL_ALL);

	  curl = curl_easy_init();
	  /* initalize custom header list (stating that Expect: 100-continue is not
	     wanted */
	  headerlist = curl_slist_append(headerlist, buf);
	  if(curl) {
	    /* what URL that receives this POST */
	    curl_easy_setopt(curl, CURLOPT_URL, "http://localhost:8080/tmanager/activity");
	      curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headerlist);
	      curl_easy_setopt(curl, CURLOPT_POST, 1);
	    curl_easy_setopt (curl, CURLOPT_POSTFIELDS,buffer);
	    res = curl_easy_perform(curl);

	    /* always cleanup */
	    curl_easy_cleanup(curl);

	    /* free slist */
	    curl_slist_free_all (headerlist);
	  }
}


void TManager::change(Activity* newActivity) {
	if (lastActivity != 0) {
		delete lastActivity;
		lastActivity = 0;
	}
	if (newActivity == 0) {
		cout << "No activity" << endl;
		return;
	}
	lastActivity = newActivity->clone();
	sendPostInfo(lastActivity);
//	cout << "PID:" << lastActivity->getId() << " app:'"
//			<< (lastActivity->getName() ? lastActivity->getName() : "(Empty)");
//	Activity* tmp = lastActivity->getSub();
//	if (tmp) {
//		cout << "' winId:" << tmp->getId() << " name:'" << (tmp->getName() ? tmp->getName()
//				: "(Empty)") << "'";
//	}
//
//	cout << endl;
}

void TManager::run() {
	if (os == 0 || os->init() == false) {
		return;
	}
	/* Бесконечный цикл обработки событий */
	while (1) {
		Activity* activity = os->getActivity();
		if (activity != 0 && !activity->equals(lastActivity)) {
			change(activity);
		}
		sleep(5);
	}
}

TManager::TManager(AbstractOS* os) {
	this->os = os;
	lastActivity = 0;
}

TManager::~TManager() {
	change(0);
}
